package ar.edu.uba.fi.jmit.monitorengine.backend.client.controller;

import java.util.List;

import ar.edu.uba.fi.jmit.monitorengine.backend.client.JMitFileService;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.JMitFileServiceAsync;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.Monitorengine;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.view.ConfigurationFilePanel;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.view.ErrorDialog;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.view.LoadedFilesPanel;
import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.JMitFileDTO;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;

public class LoadedFilesController {
	
	private Monitorengine mainModule;
	
	private LoadedFilesPanel panel;
	
	private JMitFileServiceAsync jmitFileService = GWT.create(JMitFileService.class);
	
	public LoadedFilesController(Monitorengine mainModule) {
		this.mainModule = mainModule;
		this.panel = mainModule.getLoadedFilesPanel();
		this.panel.setController(this);
	}

	public void showLoadedFiles() {
		GWT.log("Showing loaded files ");
		jmitFileService.getLoadedConfigurationFiles(new AsyncCallback<List<JMitFileDTO>>() {
			
			@Override
			public void onSuccess(List<JMitFileDTO> events) {
				mainModule.showLoadedFilesPanel();
				panel.showConfigurationFiles(events);
			}
			
			@Override
			public void onFailure(Throwable arg0) {
				//mostrar error
				GWT.log("Could not get last sended events", arg0);
				DialogBox dialog = new ErrorDialog("Could not get last sended events", arg0.getMessage(), arg0.getStackTrace());
				dialog.show();
			}
		});
		
	}

	public void deleteFile(String fileName) {
		GWT.log("deleteFile");
		jmitFileService.deleteFile(fileName, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable arg0) {
				GWT.log("Could not delete file", arg0);
				DialogBox dialog = new ErrorDialog("Could not delete file", arg0.getMessage(), arg0.getStackTrace());
				dialog.show();
			}

			@Override
			public void onSuccess(Void arg0) {
				showLoadedFiles();
			}
			
		});
		
	}

	public void showFile(String fileName) {
		GWT.log("showFile");
		jmitFileService.getFileText(fileName, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable arg0) {
				GWT.log("onFailure", arg0);
				DialogBox dialog = new ErrorDialog(arg0.getMessage(), arg0.getMessage());
				dialog.setVisible(true);
			}

			@Override
			public void onSuccess(String fileText) {
				ConfigurationFilePanel dialog = new ConfigurationFilePanel(fileText);
				dialog.center();
				dialog.show();
			}
			
		});
		
	}

}
